package com.example.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;

public class Sever {
    private static final Logger logger = LoggerFactory.getLogger(Sever.class);
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        Selector selector = Selector.open();
        ssc.bind(new InetSocketAddress( 8080));
        ssc.configureBlocking(false);
        ssc.register(selector, SelectionKey.OP_ACCEPT);
        ByteBuffer byteBuffer = ByteBuffer.allocate(15);
        while (true) {
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            SelectionKey selectionKey = iterator.next();
            logger.info("时间触发={}",selectionKey.interestOps());
            iterator.remove();
            if (selectionKey.interestOps() == SelectionKey.OP_ACCEPT) {
                SocketChannel sc = ssc.accept();
                sc.configureBlocking(false);
                sc.register(selector, SelectionKey.OP_READ);
                continue;
            }
            SocketChannel sc = (SocketChannel) selectionKey.channel();
            try {
                logger.info("连上了");
                int read = sc.read(byteBuffer);
                if (read == -1) {
                    sc.close();
                }
                byteBuffer.flip();
                System.out.println(StandardCharsets.UTF_8.decode(byteBuffer));
                byteBuffer.clear();
            } catch (IOException e) {
                e.printStackTrace();
                sc.close();
            }
        }
    }
}
